<?php
declare (strict_types = 1);
namespace app\course\model\record;

use app\common\model\BaseModel;
use app\course\logic\base\Course;
use app\course\logic\base\CourseSection;
use app\course\model\payment\PaymentOrderItem as POI;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

/**
 * 课程学习记录模型
 * @method course(mixed $courseId)
 */
class LearnCourseRecord extends BaseModel
{
    use SoftDelete;
    /**
     * 表名
     * @var string
     */
    protected $name = 'user_learn_course_record';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    protected $hidden             = ['delete_time'];
    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'          => 'integer',
        'update_time' => 'integer',
    ];

    public function scopeCourse($query, $course_id)
    {
        $query->where('course_id', $course_id);
    }

    public function scopeExistRecord($query, $course_id, $section_id, $mid = 0)
    {
        $mid = $mid ?: request()->mid;
        $query->where('course_id', $course_id);
        $query->where('section_id', $section_id);
        $query->where('user_id', $mid);
    }

    public function scopeUnfinished($query, $course_id, $mid = 0)
    {
        $mid = $mid ?: request()->mid;
        $query->where('course_id', $course_id);
        $query->where('user_id', $mid);
        $query->where('finished', 0);
    }

    public function scopeFinished($query, $course_id, $mid = 0)
    {
        $mid = $mid ?: request()->mid;
        if ( is_array($course_id) ) {
            $query->where('course_id', 'IN', $course_id);
        } else {
            $query->where('course_id', $course_id);
        }
        
        $query->where('user_id', $mid);
        $query->where('finished', 1);
    }

    public function courseData(): BelongsTo
    {
        return $this->belongsTo(Course::class, 'course_id')->with(['cover_url'])
            ->bind([
                'course_title'     => 'title',
                'course_type_text' => 'course_type_text',
                'course_cover'     => 'cover_url',
                'section_level'
            ])
        ;
    }

    public function courseOrderTermTime(): HasOne
    {
        return $this->hasOne(POI::class, 'product_id', 'course_id')
            ->where('user_id', request()->mid)
            ->whereIn('product_type_id', Course::getCourseProducts())
            ->bind(['expire_time']);
    }

    public function sectionTitle(): BelongsTo
    {
        return $this->belongsTo(CourseSection::class, 'section_id')->bind(['section_title' => 'title']);
    }

    public function sectionStock(): BelongsTo
    {
        return $this->belongsTo(CourseSection::class, 'section_id')->with(['video_attach_stock'])->bind(['stock']);
    }
}
